package argo.hot100.arr;

import java.util.Arrays;
import java.util.Random;

public class SortArr {
    public int[] sortArray(int[] nums) {
        if (nums == null || nums.length == 1) {
            return nums;
        }

        quickSort(nums, 0, nums.length - 1);
        return nums;
    }

    public void quickSort(int[] nums, int left, int right) {
        if (left < right) {

            int pivot = partition(nums, left, right);
            quickSort(nums, left, pivot - 1);
            quickSort(nums, pivot + 1, right);
        }
    }

    public int partition(int[] nums, int left, int right) {
        int rdmInx = new Random().nextInt(right - left + 1) + left;
        swap(nums, rdmInx, right);
        int pivonum = nums[right];
        int i = left;
        for (int j = left; j <= right - 1; j++) {
            if (nums[j] <= pivonum) {
                if (i != j) {
                    swap(nums, j, i);
                }
                i += 1;
            }
        }
        swap(nums, i, right);
        return i;
    }

    // 交换数组中的两个元素
    private static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(new SortArr().sortArray(new int[]{2, 7, 3, 6, 4})));
    }

}
